package me.boot.web.security.xss;

import cn.hutool.core.collection.CollUtil;
import lombok.extern.slf4j.Slf4j;
import me.boot.web.security.xss.converter.XssStringJsonDeserializer;
import me.boot.web.security.xss.filter.XssFilter;
import me.boot.web.security.xss.properties.XssProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;

/**
 * XSS 跨站攻击自动配置
 */
@Slf4j
@Configuration(proxyBeanMethods = false)
@EnableConfigurationProperties({XssProperties.class})
public class XssConfiguration {

    @Autowired
    XssProperties properties;

    @PostConstruct
    void init() {
        log.info("Init XssConfiguration");
    }

    /**
     * 配置跨站攻击 反序列化处理器
     */
    @Bean
    public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer2() {
        return builder -> {
            if (properties.isRequestBodyEnabled()) {
                builder.deserializerByType(String.class, new XssStringJsonDeserializer());
            }
        };
    }


    /**
     * 配置跨站攻击过滤器
     */
    @Bean
    @ConditionalOnProperty(prefix = XssProperties.PREFIX, name = "enabled", havingValue = "true", matchIfMissing = true)
    public FilterRegistrationBean<?> filterRegistrationBean() {
        FilterRegistrationBean<XssFilter> filterRegistration = new FilterRegistrationBean<>();
        filterRegistration.setFilter(new XssFilter());
        filterRegistration.setEnabled(properties.isEnabled());
        filterRegistration.addUrlPatterns(properties.getPatterns().toArray(new String[0]));
        filterRegistration.setOrder(properties.getOrder());

        Map<String, String> initParameters = new HashMap<>(4);
        initParameters.put(XssFilter.IGNORE_PATH, CollUtil.join(properties.getIgnorePaths(), ","));
        initParameters.put(XssFilter.IGNORE_PARAM_VALUE, CollUtil.join(properties.getIgnoreParamValues(), ","));
        filterRegistration.setInitParameters(initParameters);
        return filterRegistration;
    }

}
